import ast
import os

import yaml

from utils.read_files_tools.regular_control import regular


class GetYamlData:

    def __init__(self, file_path):
        self.file_path = str(file_path)

    def get_yaml_data(self) -> dict:
        if not os.path.exists(self.file_path):
            raise FileNotFoundError(f"yaml文件不存在{self.file_path}")

        data = open(self.file_path, "r", encoding="utf-8")
        res = yaml.load(data, Loader=yaml.FullLoader)
        return res

    def write_yaml_data(self, key: str, value) -> int:
        '''
        修改yaml值，并且保留注释
        :param data:
        :return:
        '''
        with open(self.file_path, 'r', encoding='utf-8') as file:
            # 创建了一个空列表，里面没有元素
            lines = []
            for line in file.readlines():
                if line != '\n':
                    lines.append(line)
            file.close()

        with open(self.file_dir, 'w', encoding='utf-8') as file:
            flag = 0
            for line in lines:
                left_str = line.split(":")[0]
                if key == left_str.lstrip() and '#' not in line:
                    newline = f"{left_str}: {value}"
                    line = newline
                    file.write(f'{line}\n')
                    flag = 1
                else:
                    file.write(f'{line}')
            file.close()
            return flag

class GetCaseDate(GetYamlData):

    def get_yaml_case_data(self):
        _yaml_data = self.get_yaml_data()
        # 替换模板数据
        re_data = regular(str(_yaml_data))
        return ast.literal_eval(re_data)